package com.ht.shop.dao.impl;

import com.ht.shop.dao.CartDao;
import com.ht.shop.pojo.CartItem;
import com.ht.shop.utils.DBUtils;
import com.ht.shop.utils.SqlUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CartDaoImpl implements CartDao {
    private QueryRunner queryRunner = new QueryRunner(DBUtils.getSource());

    @Override
    public Long findCountByUidAndPid(String pid, long uid) {
        String sql = SqlUtils.getSql("cart.selectcount");
        long count = 0;
        try {
            count = queryRunner.query(sql,new ScalarHandler<>(),uid,pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    @Override
    public void addCart(String pid, long uid, int num) throws SQLException {
        String sql = SqlUtils.getSql("cart.add");
        queryRunner.insert(sql,new ScalarHandler<>(),uid,pid,num);
    }

    @Override
    public int updateNum(String pid, long uid, int num) throws SQLException {
        String sql = SqlUtils.getSql("cart.updatenum");

        return queryRunner.update(sql,num,uid,pid);
    }

    @Override
    public List<CartItem> findCartByUid(long uid) {
        String sql = SqlUtils.getSql("cart.selectbyuid");
        try {
            List<CartItem> cartItemList = queryRunner.query(sql, new BeanListHandler<>(CartItem.class), uid);
            return cartItemList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public void deleteByUid(long uid) {
        String sql = SqlUtils.getSql("cart.delete");
        try {
            queryRunner.update(sql,uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
